import {formatGMTDate} from '../../../assets/js/util.js';

export default {
	data() {
		return{
			pageSize:10,
			/*每页显示的数量*/
			pageSizes:[10, 20, 50, 100],
			/*dataTotal表数量*/
			dataTotal:0,
			/*分页器*/
			currentPage: 1,
			games:[],
			revampShow: false,
			options: [],
			pausePd: '',
			SRC: '',
			rules: {
				addId: [
					{ pattern: /^[0-9]*$/, message: '监控ID必须为数字值', trigger: 'blur,change' }
				],
				addMoniDesc: [
					
				],
				addMoniState: [
					
				],
				addMoniThres: [
					{ pattern: /^[0-9]*$/, message: '监控阈值必须为数字值', trigger: 'blur,change' }
				],
				addMoniFreq: [
					{ pattern: /^[0-9]*$/, message: '监控频率（分钟）必须为数字值', trigger: 'blur,change' }
				],
				addMoniNumb: [
					{ pattern: /^[0-9]*$/, message: '监控次数必须为数字值', trigger: 'blur,change' }
				],
				addMoniOut: [
				]
			},
			ruleForm: {
				addId: '',
				addGameName: '',
				addGameID: '',
				addMoniDesc: '',
				addMoniState: '',
				addMoniThres: '',
				addStartDate: '',
				addEndDate: '',
				addMoniFreq: '',
				addMoniNumb: '',
				addMoniOut: '',
				addMoniGroup: '',
				addMoniGroupName: '',
			},
			revampForm: {
				addId: '',
				addGameName: '',
				addGameID:'',
				addMoniDesc: '',
				addMoniState: '',
				addMoniThres: '',
				addStartDate: '',
				addEndDate: '',
				addMoniFreq: '',
				addMoniNumb: '',
				addMoniOut: '',
				addMoniGroup: '',
				addMoniGroupName: '',
			},
			tableHeader: [
			    {"prop":"id","label":"监控id"},
			    {"prop":"gameName","label":"工程名称"},
			    {"prop":"gameId","label":"工程ID"},
			    {"prop":"status","label":"监控状态"},	
			    {"prop":"description","label":"监控描述"},
			    {"prop":"inquerySQL","label":"监控语句"},
			    {"prop":"threshHold","label":"监控阈值"}, 
			    {"prop":"startTime","label":"开始日期"},
				{"prop":"endTime","label":"结束日期"},
				{"prop":"intervalTime","label":"监控频率（分钟）"},
				{"prop":"countNum","label":"监控次数"},
				{"prop":"subDescription","label":"监控产出说明"},
				{"prop":"groupName","label":"监控组别"},
			],
			tableData: [],
		} 
	},
	methods: {
		handleSizeChange(val) {
	      this.pageSize = val;
	      var url = this.urlUrl;
	      this.findDate ();
	    },
	    // 页数
	    handleCurrentChange(val) {
	      this.currentPage = val;
	      this.findDate ();
	    },
	    resetForm(formName) {
			this.$refs[formName].resetFields();
			this.ruleForm.addGameID = '';
			console.log(this.ruleForm)
		},
		changeDate1 (val) {
			// console.log(this.ruleForm.addStartDate)
			// this.ruleForm.addStartDate=val;
		},
		changeDate2 (val) {
			// this.ruleForm.addEndDate=val;
		},
		gameChange (value) {
			for (var i in this.games) {
				if (value === this.games[i]['id']) {
					this.ruleForm.addGameName = this.games[i]['projectName'];
				}else if(value === this.games[i]['projectName']){
					this.ruleForm.addGameID = this.games[i]['id'];
				}
			}
			/*console.log(this.ruleForm.addGameName,this.ruleForm.addGameID)*/
		},
		gameChange2 (value) {
			for (var i in this.games) {
				if (value === this.games[i]['id']) {
					this.revampForm.addGameName = this.games[i]['projectName'];
				}else if(value === this.games[i]['projectName']){
					this.revampForm.addGameID = this.games[i]['id'];
				}
			}
			/*console.log(this.revampForm.addGameName,this.revampForm.addGameID)*/
		},
		groupChange (value) {
			for (var i in this.options) {
				if (value === this.options[i]['id']) {
					this.ruleForm.addMoniGroupName = this.options[i]['groupName'];
				}else if(value === this.options[i]['groupName']){
					this.ruleForm.addMoniGroup = this.options[i]['id'];
				}
			}
			console.log(this.options);
		},
		groupChange2 (value) {
			for (var i in this.options) {
				if (value === this.options[i]['id']) {
					this.revampForm.addMoniGroupName = this.options[i]['groupName'];
				}else if(value === this.options[i]['groupName']){
					this.revampForm.addMoniGroup = this.options[i]['id'];
				}
			}
			console.log(this.options);
		},
		/*============== 通用 成功 与 失败==============*/
	    successFun(data) {
	      this.$message({
	        message: data,
	        type: 'success'
	      });
	    },
	    errorFun(data) {
	      this.$message.error(data);
	    },
	    /*==============废除一个告警配置==============*/
	    handleDelete(index, row) {
	      var tableDataCP = this.tableData;
	      /*this.tableData.splice(index,1);*/
	      this.$http.get(`${this.SRC}monitorconfig/abandonJob.do?id=${row.id}`).then(function(res){
	      	var data = res.body;
	      	if(parseInt(data['code']) === 0){
	      		this.successFun(data['msg']);
	      		this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
	      	}else{
	      		this.errorFun(data['msg']);
	      		this.tableData = this.tableDataCP;
	      	}
	      })
	    },
        /*==============暂停一个任务==============*/
		pauseCur(index, row ) {
			var tableDataCP = this.tableData;
			this.$http.get(`${this.SRC}monitorconfig/pauseJob.do?id=${row.id}`).then(function(res){
				var data = res.body;
				if(parseInt(data['code']) === 0){
					this.successFun(data['msg']);
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}else{
					this.errorFun(data['msg']);
					this.tableData = this.tableDataCP;
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}
			})
		},
        /*==============恢复一个任务==============*/
        restCur (index, row ) {
    		var tableDataCP = this.tableData;
    		row.startTime = new Date(row.startTime).getTime();
    		row.endTime = new Date(row.endTime).getTime();
    		var obj = {
    			id: row.id,
    			inquerySQL: row.inquerySQL,
    			description: row.description,
    			subDescription: row.subDescription,
    			groupId: row.groupId,
    			threshHold: row.threshHold,
    			status: row.status,
    			creatTime: row.creatTime,
    			starttime: row.startTime,
    			endtime: row.endTime,
    			intervalTime: row.intervalTime,
    			countNum: row.countNum,
    			gameId: row.gameId
    		}
        	this.$http.post(`${this.SRC}monitorconfig/resumeJob.do`,obj,{emulateJSON:true}).then(function(res){
				var data = res.body;
				if(parseInt(data['code']) === 0){
					this.successFun(data['msg']);
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}else{
					this.errorFun(data['msg']);
					this.tableData = this.tableDataCP;
				}
			})
        },
        /*==============开始所有任务==============*/
        startAll () {
        	if(this.ruleForm['addGameID'] === ''){
				this.errorFun("请先选择工程！")
				return;
			}
        	var tableDataCP = this.tableData;
        	this.$http.get(`${this.SRC}monitorconfig/startAll.do?gameId=${this.ruleForm.addGameID}`).then(function(res){
				var data = res.body;
				if(parseInt(data['code']) === 0){
					this.successFun(data['msg']);
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}else{
					this.errorFun(data['msg']);
					this.tableData = this.tableDataCP;
				}
			})
        },
        /*==============暂停所有任务==============*/
        pauseAll () {
        	if(this.ruleForm['addGameID'] === ''){
				this.errorFun("请先选择工程！")
				return;
			}
        	var tableDataCP = this.tableData;
        	this.$http.get(`${this.SRC}monitorconfig/pauseAll.do?gameId=${this.ruleForm.addGameID}`).then(function(res){
				var data = res.body;
				if(parseInt(data['code']) === 0){
					this.successFun(data['msg']);
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}else{
					this.errorFun(data['msg']);
					this.tableData = this.tableDataCP;
				}
			})
        },
        /*==============恢复所有任务==============*/
        restAll () {
        	if(this.ruleForm['addGameID'] === ''){
				this.errorFun("请先选择工程！")
				return;
			}
        	var tableDataCP = this.tableData;
        	this.$http.get(`${this.SRC}monitorconfig/resumeAll.do?gameId=${this.ruleForm.addGameID}`).then(function(res){
				var data = res.body;
				if(parseInt(data['code']) === 0){
					this.successFun(data['msg']);
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}else{
					this.errorFun(data['msg']);
					this.tableData = this.tableDataCP;
				}
			})
        },
	    /*==============添加告警配置==============*/
	    addForm (formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.addAlarmData();
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				} else {
					return false;
				}
			});
		},
		addAlarmData() {
			console.log(this.ruleForm)
			for(var i in this.ruleForm){
				if(this.ruleForm[i] === ''){
					this.errorFun("添加不能为空！")
					return;
				}
			}
			var obj = {
				id: this.ruleForm.addId,
				inquerySQL: this.ruleForm.addMoniState,
				description: this.ruleForm.addMoniDesc,
				subDescription: this.ruleForm.addMoniOut,
				groupId: this.ruleForm.addMoniGroup,
				threshHold: this.ruleForm.addMoniThres,
				starttime: new Date(this.ruleForm.addStartDate).getTime(),
				endtime: new Date(this.ruleForm.addEndDate).getTime(),
				intervalTime: this.ruleForm.addMoniFreq,
				countNum: this.ruleForm.addMoniNumb,
				gameName: this.ruleForm.addGameName,
				gameId: this.ruleForm.addGameID
			};
			this.$http.post(`${this.SRC}monitorconfig/addStart.do`,obj,{emulateJSON:true}).then(function(res){
				// console.log(res)
				var data = res.body;
				// console.log(data)
				if(parseInt(data["code"]) === 0){
					this.successFun(data["msg"])
					this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
				}else{
					this.errorFun(data['msg'])
				}
			})
		},
		/*==============修改提交==============*/
		edit (index, row) {
			if(row.show3 === true){
				this.revampForm.addId = row.id;
				this.revampForm.addGameID = row.gameId;
				this.revampForm.addStatus = row.status;
				this.revampForm.addGameName = row.gameName;
				this.revampForm.addMoniDesc = row.description;
				this.revampForm.addMoniState = row.inquerySQL;
				this.revampForm.addMoniThres = row.threshHold;
				this.revampForm.addStartDate = row.startTime;
				this.revampForm.addEndDate = row.endTime;
				this.revampForm.addMoniFreq = row.intervalTime;
				this.revampForm.addMoniNumb = row.countNum;
				this.revampForm.addMoniOut = row.subDescription;
				this.revampForm.addMoniGroup = row.groupId;
				this.revampShow = true;
			}else{
				this.restCur(index, row);
				this.findForm();
			}
			
		},
		revampComit(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					var d = this.revampForm;
					var obj = {
						id: d.addId,
						inquerySQL: d.addMoniState,
						description: d.addMoniDesc,
						subDescription: d.addMoniOut,
						groupId: d.addMoniGroup,
						threshHold: d.addMoniThres,
						status: d.addStatus,
						starttime: new Date(d.addStartDate).getTime(),
						endtime: new Date(d.addEndDate).getTime(),
						intervalTime: d.addMoniFreq,
						countNum: d.addMoniNumb,
						gameName: d.addGameName,
						gameId: d.addGameID
					}

					this.$http.post(`${this.SRC}monitorconfig/modify.do`,obj,{emulateJSON:true}).then(function(res){
						var data = res.body;
						if(parseInt(data['code']) === 0){
							this.successFun(data['msg']);
							this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`);
						}else{
							this.errorFun(data['msg'])
						}
					})
				} else {
					return false;
				}
			});
		},
		/*==============查询功能=============*/
        findForm (formName) {
        	var tableDataCP = this.tableData;
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.findDate();
				} else {
					return false;
				}
			});
		},
        findDate () {
        	var d = this.ruleForm;
			var obj = {
				id: d.addId,
				inquerySQL: d.addMoniState,
				description: d.addMoniDesc,
				subDescription: d.addMoniOut,
				groupId: d.addMoniGroup,
				threshHold: d.addMoniThres,
				status: d.addMoniGroup,
				starttime: new Date(this.ruleForm.addStartDate).getTime(),
				endtime: new Date(this.ruleForm.addEndDate).getTime(),
				intervalTime: d.addMoniFreq,
				countNum: d.addMoniNumb,
				gameName: d.addGameName
			}
			var str = '';
			for(var i in obj){
				if(obj[i] !== ""){
					str += `${i}=${obj[i]}&`
				}
			}
			str = str.substring(0,str.length-1);
			this.$http.get(`${this.SRC}monitorconfig/list.do?curPage=${this.currentPage}&pageSize=${this.pageSize}&`+str).then(function(res){
				var data = res.body;
				if(parseInt(data['code']) === 0){
					if(data.msg.data.length == 0){
						this.errorFun('查询无结果！');
					}else{
						this.successFun('查询成功！');
					}
					var tempData = data.msg.data;
					for(var x=0,len=tempData.length;x<len;x++){
						for(var y=0,len1=this.options.length;y<len1;y++){
							if(tempData[x]['groupId'] == this.options[y]['id']){
								tempData[x]['groupName'] =  this.options[y]['groupName'];
							}
						}
					}
					for(var x=0,len=tempData.length;x<len;x++){
						for(var y=0,len1=this.games.length;y<len1;y++){
							if(tempData[x]['gameId'] == this.games[y]['id']){
								tempData[x]['gameName'] =  this.games[y]['projectName'];
							}
						}
					}
					this.tableData = data.msg.data;
					this.currentPage = data.msg.curPage;
					this.pageSize = data.msg.pageSize;
					this.dataTotal = data.msg.totalSize;
					var d = data.msg.data;
					for(var i=0; i<d.length; i++){
						if(d[i]['status'] === 'COMPLETE'){
							d[i]['show1'] = false;
							d[i]['show2'] = false;
							d[i]['show3'] = false;
						}else if(d[i]['status'] === 'PAUSED'){
							d[i]['show1'] = false;
							d[i]['show2'] = true;
							d[i]['show3'] = true;
						}else if(d[i]['status'] === 'NORMAL'){
							d[i]['show1'] = true;
							d[i]['show2'] = false;
							d[i]['show3'] = true;
						}else if(d[i]['status'] === 'NONE'){
							d[i]['show1'] = false;
							d[i]['show2'] = false;
							d[i]['show3'] = false;
						}
					}
				}else{
					this.errorFun(data['msg'])
				}
			})
        },
		/*==============获取数据==============*/
		getTableData(src) {
			var that = this;
			function post(url) {
				return new Promise(
					function(resolve,reject){
						that.$http.post(that.SRC+url).then(function(res){
							if(res.body['code'] === 0){
			                  resolve(res.body['msg']);
			                }else{
			                  reject(false);
			                }
						})
					}	
				)
			};
			var urlData = ["project/list.do","monitorgroup/list.do","monitorconfig/list.do?"+src];
			function renderAll() {
				return Promise.all([post(urlData[0]), post(urlData[1]),post(urlData[2])]);
			};
			renderAll().then(function(value){
				that.games = value[0];
				that.options = value[1];
				var tempData = value[2].data;
				for(var x=0,len=tempData.length;x<len;x++){
					for(var y=0,len1=that.options.length;y<len1;y++){
						if(tempData[x]['groupId'] == that.options[y]['id']){
							tempData[x]['groupName'] =  that.options[y]['groupName'];
						}
					}
				}
				for(var x=0,len=tempData.length;x<len;x++){
					for(var y=0,len1=that.games.length;y<len1;y++){
						if(tempData[x]['gameId'] == that.games[y]['id']){
							tempData[x]['gameName'] =  that.games[y]['projectName'];
						}
					}
				}
				that.tableData = tempData;
				that.dataTotal = value[2].totalSize;
				var d = value[2].data;
				for(var i=0; i<d.length; i++){
					if(d[i]['status'] === 'COMPLETE'){
						d[i]['show1'] = false;
						d[i]['show2'] = false;
						d[i]['show3'] = false;
					}else if(d[i]['status'] === 'PAUSED'){
						d[i]['show1'] = false;
						d[i]['show2'] = true;
						d[i]['show3'] = true;
					}else if(d[i]['status'] === 'NORMAL'){
						d[i]['show1'] = true;
						d[i]['show2'] = false;
						d[i]['show3'] = true;
					}else if(d[i]['status'] === 'NONE'){
						d[i]['show1'] = false;
						d[i]['show2'] = false;
						d[i]['show3'] = false;
					}
				}
			})
		}
	},
	created () {
		// console.log(new Date('2017-06-10').getTime(),new Date('2017-09-10').getTime())
		this.SRC = this.$store.getters.src3;
		this.getTableData(`curPage=${this.currentPage}&pageSize=${this.pageSize}`)
	}
} 